<template>
  <base-search
    :title="t('keys.Message_List')"
    :isShowSearch="selectionRowData.length"
    :schema="searchData"
    :acitveName="activeName"
    @search-submit="searchSubmit"
    @reset-submit="resetSubmit"
  >
    <template #btn>
      <el-button type="primary" @click="allread">{{ t('keys.all_read') }}</el-button>
    </template>
  </base-search>

  <base-table
    ref="tableRefCom"
    v-loading="loading"
    border
    selection
    reserveSelection
    :row-style="{ cursor: 'pointer' }"
    row-key="webMsgId"
    rowKey="webMsgId"
    :columns="columns"
    :data="tableData"
    :pagination="{
      currentPage: searchValue.page,
      total: total,
      onSizeChange: handleSizeChange,
      onCurrentChange: handleCurrentChange
    }"
    @row-click="onRowClick"
    @selection-change="handleSelectionChange"
  >
    <!-- 批量按钮 -->
    <template #btn>
      <el-button type="info" @click="handleAlllClick(1)">{{ t('keys.mark_Read') }}</el-button>
      <el-button type="info" @click="handleAlllClick(2)">{{ t('keys.BatchDelete') }}</el-button>
    </template>
    <template #messageTitle="scope">
      <div>
        <el-button type="info" link @click.stop="goDetails(scope.row)"
          ><span :class="scope.row.readFlag ? 'spotNone' : 'spot'">{{ scope.row.messageTitle }}</span></el-button
        >
      </div>
    </template>
    <!-- <template #messageContent="scope">
      <div v-if="scope.row.messageContent">{{ escape2Html(scope.row.messageContent.replace(/<[^<>]+>/g, '').replace(/&nbsp;/gi, '')) }}</div>
    </template> -->
    <template #action="scope">
      <el-button @click.stop="goDetails(scope.row)" type="info" link>{{ t('keys.Detail') }}</el-button>
    </template>
  </base-table>

  <zcb-dialog v-model="dialogShow" :title="t('keys.Message_details')" dialogWidth="744px">
    <div v-if="dialogShow">
      <div class="wraps">
        <div class="wraps_title">{{ detailsData.messageTitle }}</div>
        <div class="wraps_time">{{ detailsData.createdTime }}</div>
        <div class="wraps_cont" v-html="detailsData.messageContent"></div>
      </div>
    </div>
    <template #btns>
      <div class="drawer__button--wrap drawer_center">
        <el-button type="info" @click="dialogShow = !dialogShow">
          {{ t('keys.cancel') }}
        </el-button>
      </div>
    </template>
  </zcb-dialog>
</template>

<script setup>
import { ref, reactive, onActivated } from 'vue'
// import ZcbSearch from 'components/zcb-search'
import { msgOptions } from 'config/mockData'

import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { webmsgListApi, webmsgdeleApi, webmsgAllReadApi, webmsgHaveReadApi, getWebMsgIconListApi, webmsgIdApi } from 'api/common/message'
import { ERR_OK } from 'config/statusCode'
// import baseDialog from 'components/base-dialog/index.vue'
import { useBasicData } from './hooks/useBasicData'
import { formatTime } from 'utils/tools.js'
import { useI18n } from 'vue-i18n'
const { t } = useI18n() // 中英文
const store = useStore()
const router = useRouter()

const activeName = ref('first')
const searchData = [
  {
    field: 'messageTitle',
    label: t('keys.Message_Title'),
    component: 'Input'
  },
  {
    field: 'createTime',
    label: t('keys.Message_time'),
    component: 'DateTimeRange'
  },
  {
    field: 'readFlag',
    label: t('keys.status'),
    component: 'Select',
    options: msgOptions()
  }
]
const columns = ref([
  {
    field: 'messageTitle',
    label: t('keys.Message_Title'),
    showOverflowTooltip: true
  },
  // {
  //   field: 'messageContent',
  //   label: t('keys.Message_content'),
  //   showOverflowTooltip: true
  // },
  {
    field: 'createdTime',
    label: t('keys.createdTime'),
    showOverflowTooltip: true,
    width: '160px'
  },
  {
    field: 'action',
    label: t('keys.operation'),
    width: '160px',
    fixed: 'right',
    slots: {
      header: 'action',
      default: ''
    }
  }
])

const {
  tableRefCom,
  defaultParams,
  selectionRowData,
  tableData,
  loading,
  total,
  rowData,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  onRowClick,
  clearSelectionKeys,
  getList,
  resetSubmit,
  searchSubmit
} = useBasicData({
  listFun: webmsgListApi
})
const searchValue = reactive({
  messageTitle: '',
  createTime: [],
  sendStartTime: '',
  sendEndTime: '',
  readFlag: ''
})

getList(searchValue)

// 每次都执行
onActivated(() => {
  getList()
})
// 批量操作
const handleAlllClick = async (num) => {
  if (selectionRowData.value.length === 0) {
    ElMessage({
      showClose: true,
      message: t('keys.please_select_table_line'),
      type: 'warning'
    })
  } else {
    ElMessageBox.confirm(
      `${t('keys.lease_tips')}${num == 1 ? t('keys.mark_Read') : t('keys.delete')}${selectionRowData.value.length}${t('keys.strip') +
        t('keys.is_it')}`,
      t('keys.tips'),
      {
        type: 'warning',
        confirmButtonText: t('keys.ok'),
        cancelButtonText: t('keys.cancel')
      }
    ).then(async () => {
      if (num == 1) {
        // 标记已读
        const res = await webmsgHaveReadApi(selectionRowData.value)
        if (res.code == ERR_OK) {
          ElMessage.success(t('keys.mark_Read') + t('keys.success'))
          tableRefCom.value.clearSelected()
          getList(searchValue)
          getreadList()
        }
      } else if (num == 2) {
        // 批量删除
        const res = await webmsgdeleApi(selectionRowData.value)
        if (res.code == ERR_OK) {
          ElMessage.success(t('keys.delete_succeeded'))
          tableRefCom.value.clearSelected()
          getList(searchValue)
          getreadList()
        }
      }
    })
  }
}
// 标记为全部已读
const allread = () => {
  ElMessageBox.confirm(`${t('keys.AreYouSureToMarkAllread')}？`, t('keys.tips'), {
    type: 'warning',
    confirmButtonText: t('keys.ok'),
    cancelButtonText: t('keys.cancel')
  })
    .then(async () => {
      const res = await webmsgAllReadApi(selectionRowData.value)
      if (res.code == ERR_OK) {
        ElMessage.success(t('keys.Markallreadsuccessfully'))
        tableRefCom.value.clearSelected()
        getList(searchValue)
        getreadList()
      }
    })
    .catch(() => {})
}
const getreadList = async () => {
  const { code, data } = await getWebMsgIconListApi()
  if (code == ERR_OK) {
    let messageList = data.messageList || []
    if (messageList.length > 0) {
      messageList.forEach((item) => {
        item.messageContent = escape2Html(item.messageContent.replace(/<[^<>]+>/g, '').replace(/&nbsp;/gi, ''))
        item.createdTime = formatTime(new Date(item.createdTime).getTime() / 1000, '')
      })
    }
    let msgObj = {
      msgList: messageList,
      msgTotle: data.totle || 0
    }
    let initStore = store.state.global.msg
    initStore.msgObj = msgObj
    store.dispatch('global/setGlobalState', { msg: initStore })
  }
}
const escape2Html = (str) => {
  var arrEntities = { lt: '<', gt: '>', nbsp: ' ', amp: '&', quot: '"' }
  return str.replace(/&(lt|gt|nbsp|amp|quot);/gi, function(all, t) {
    return arrEntities[t]
  })
}

// const goDetails = (row) => {
//   router.push({
//     name: 'msgCenterDetails',
//     query: { sourceType: row.sourceType || '', messageId: row.messageId || '' }
//   })
// }
// 申请弹板
const dialogShow = ref(false)
const detailsData = ref({})
const goDetails = async (row) => {
  const { code, data } = await webmsgIdApi(row.messageId, { sourceType: row.sourceType })
  if (code == ERR_OK) {
    detailsData.value = data || {}
    dialogShow.value = true
    getList()
    getreadList()
  }
}

const submitFormdialog = async () => {
  dialogShow.value = false
  loading.value = true
  const { code, data } = await getProductBuyApplyApi(formData.value)
  if (code === ERR_OK) {
    ElMessage({
      message: t('keys.apply_successes'),
      type: 'success'
    })
    loading.value = false
    getList()
  } else {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.wrap {
  margin: 0;
  .wrap_ul {
    width: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 34px;
    .wrap_li {
      color: #666666;
      font-size: 16px;
      font-weight: 400;
      margin-right: 24px;
      position: relative;
      cursor: pointer;
      .wrap_li_line {
        display: inline-block;
        position: absolute;
        left: 0;
        bottom: -10px;
        width: 48px;
        height: 2px;
        background: #1ba1ba;
      }
    }
    .wrap_licur {
      color: #1ba1ba;
      font-weight: 600;
    }
  }
}
.el-button {
  min-width: 88px;
}

.spot {
  margin-left: 16px;
  cursor: pointer;
}
.spotNone {
  cursor: pointer;
  margin-left: 16px;
}
.spot::after {
  content: '';
  display: block;
  position: absolute;
  width: 6px;
  height: 6px;
  left: 10px;
  top: 18px;
  border-radius: 8px;
  background: var(--el-color-primary);
}

.wraps {
  margin-top: 16px;
  font-size: 14px;
  line-height: 22px;
  .wraps_title {
    width: 100%;
    font-size: 16px;
    font-weight: 550;
    color: #333333;
    line-height: 24px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
    word-wrap: break-word;
    word-break: break-all;
    text-overflow: ellipsis;
  }
  .wraps_time {
    margin-top: 8px;
    font-size: 14px;
    font-weight: 400;
    color: #666666;
  }
  .wraps_cont {
    width: 100%;
    margin-top: 20px;
    p {
      word-break: break-all;
    }
  }
}
.drawer_center {
  width: 100%;
  text-align: right;
  margin-top: 20px;
}
</style>
